import 'dart:convert';

/// 好友申请列表请求模型
class FriendRequestListRequest {
  final int userId;
  final int timestamp;

  FriendRequestListRequest({
    required this.userId,
    int? timestamp,
  }) : timestamp = timestamp ?? DateTime.now().millisecondsSinceEpoch ~/ 1000;

  Map<String, dynamic> toJson() {
    return {
      'user_id': userId,
      'timestamp': timestamp,
    };
  }
}

/// 好友申请信息模型
class FriendRequestInfo {
  final int requestId;
  final int senderId;
  final int receiverId;
  final String status; // pending/accepted/rejected
  final String? message;
  final String? source;
  final String createdAt;
  final String? expiredAt;
  final String? processedAt;
  final String updatedAt;
  // 发送者信息（从嵌套的用户信息中获取）
  final int? userId;
  final String? senderUsername;
  final String? senderPhone;
  final String? senderBirthday;
  final String? senderAvatar;
  final String? senderSignature;
  final String? senderGender;
  final int? senderAge;
  final String? senderCity;
  final List<String>? senderTags;
  final List<String>? senderHobbies;
  final int? senderLevel;

  FriendRequestInfo({
    required this.requestId,
    required this.senderId,
    required this.receiverId,
    required this.status,
    this.message,
    this.source,
    required this.createdAt,
    this.expiredAt,
    this.processedAt,
    required this.updatedAt,
    this.userId,
    this.senderUsername,
    this.senderPhone,
    this.senderBirthday,
    this.senderAvatar,
    this.senderSignature,
    this.senderGender,
    this.senderAge,
    this.senderCity,
    this.senderTags,
    this.senderHobbies,
    this.senderLevel,
  });

  factory FriendRequestInfo.fromJson(Map<String, dynamic> json) {
    // 将数字状态转换为字符串状态
    String statusStr;
    final statusValue = json['status'];
    final processedAt = json['processed_at'];
    
    if (statusValue is int) {
      switch (statusValue) {
        case 0:
          statusStr = 'pending';
          break;
        case 1:
          // status=1 需要根据 processed_at 判断具体状态
          if (processedAt != null) {
            statusStr = 'accepted';  // 已同意
          } else {
            statusStr = 'pending';   // 待处理
          }
          break;
        case 2:
          statusStr = 'rejected';
          break;
        case 3:
          // status=3 根据是否有好友关系来判断：如果有好友关系说明是已同意，否则是已拒绝
          // 但这里先统一处理为 accepted，让UI层决定如何显示
          statusStr = 'accepted';  // status=3 表示已处理并建立好友关系
          break;
        default:
          statusStr = 'pending';
      }
    } else {
      statusStr = statusValue?.toString() ?? 'pending';
    }

    // 解析用户标签
    List<String>? parsedTags;
    if (json['userTags'] != null) {
      final tagsValue = json['userTags'];
      if (tagsValue is String) {
        try {
          // 如果是JSON字符串，尝试解析
          final List<dynamic> tagsList = jsonDecode(tagsValue);
          parsedTags = tagsList.cast<String>();
        } catch (e) {
          // 解析失败，使用默认值
          parsedTags = [];
        }
      } else if (tagsValue is List) {
        parsedTags = tagsValue.cast<String>();
      }
    }

    // 解析用户爱好
    List<String>? parsedHobbies;
    if (json['userHobbies'] != null) {
      final hobbiesValue = json['userHobbies'];
      if (hobbiesValue is String) {
        try {
          final List<dynamic> hobbiesList = jsonDecode(hobbiesValue);
          parsedHobbies = hobbiesList.cast<String>();
        } catch (e) {
          parsedHobbies = [];
        }
      } else if (hobbiesValue is List) {
        parsedHobbies = hobbiesValue.cast<String>();
      }
    }

    return FriendRequestInfo(
      requestId: json['request_id'] ?? 0,
      senderId: json['sender_id'] ?? 0,
      receiverId: json['receiver_id'] ?? 0,
      status: statusStr,
      message: json['message'],
      source: json['source'],
      createdAt: json['created_at'] ?? '',
      expiredAt: json['expired_at'],
      processedAt: json['processed_at'],
      updatedAt: json['updated_at'] ?? '',
      userId: json['userid'],
      senderUsername: json['username'],
      senderPhone: json['userPhone'],
      senderBirthday: json['userBirthday'],
      senderAvatar: json['userAvatarUrl'],
      senderSignature: json['userSignature'],
      senderGender: json['userGender'],
      senderAge: json['userAge'],
      senderCity: json['userCity'],
      senderTags: parsedTags,
      senderHobbies: parsedHobbies,
      senderLevel: json['userLevel'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'request_id': requestId,
      'sender_id': senderId,
      'receiver_id': receiverId,
      'status': status,
      'message': message,
      'source': source,
      'created_at': createdAt,
      'expired_at': expiredAt,
      'processed_at': processedAt,
      'updated_at': updatedAt,
      'userid': userId,
      'username': senderUsername,
      'userPhone': senderPhone,
      'userBirthday': senderBirthday,
      'userAvatarUrl': senderAvatar,
      'userSignature': senderSignature,
      'userGender': senderGender,
      'userAge': senderAge,
      'userCity': senderCity,
      'userTags': senderTags != null ? jsonEncode(senderTags) : null,
      'userHobbies': senderHobbies != null ? jsonEncode(senderHobbies) : null,
      'userLevel': senderLevel,
    };
  }
}

/// 好友申请列表响应模型
class FriendRequestListResponse {
  final String status;
  final int count;
  final List<FriendRequestInfo> data;
  final String? message;

  FriendRequestListResponse({
    required this.status,
    required this.count,
    required this.data,
    this.message,
  });

  bool get isSuccess => status == 'success';

  factory FriendRequestListResponse.fromJson(Map<String, dynamic> json) {
    return FriendRequestListResponse(
      status: json['status'] ?? 'error',
      count: json['count'] ?? 0,
      data: (json['data'] as List?)
          ?.map((item) => FriendRequestInfo.fromJson(item))
          .toList() ?? [],
      message: json['message'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'status': status,
      'count': count,
      'data': data.map((request) => request.toJson()).toList(),
      if (message != null) 'message': message,
    };
  }
}
